#include "STLModelMeshesConvertor.h"

// 需要去重
bool PointCloudConvertor::convertFrom(const QVector<Mesh> &stl_meshes)
{
    if(stl_meshes.empty())
        return false;

    for (const Mesh& mesh : stl_meshes) {
        // 每个三角形面片有三个顶点
        Vertex v1, v2, v3;
        v1.pos = mesh.v1;
        v1.color = {0.5f, 0.5f, 0.5f, 1.0f};
        v1.norm = mesh.normal;
        v2.pos = mesh.v2;
        v2.color = {0.5f, 0.5f, 0.5f, 1.0f};
        v2.norm = mesh.normal;
        v3.pos = mesh.v3;
        v3.color = {0.5f, 0.5f, 0.5f, 1.0f};
        v3.norm = mesh.normal;

        // 添加顶点数据
        m_stl_model_vertices.append(v1);
        m_stl_model_vertices.append(v2);
        m_stl_model_vertices.append(v3);
    }

    return true;
}

QVariant PointCloudConvertor::getModel() const
{
    return QVariant::fromValue(m_stl_model_vertices);
}

bool EdgesConvertor::convertFrom(const QVector<Mesh> &stl_meshes)
{
    QSet<Edge> uniqueEdges;

    auto compareQVector3D = [](const QVector3D& v1, const QVector3D& v2) -> bool {
        return v1.lengthSquared() < v2.lengthSquared();
    };

    for (const Mesh &mesh : stl_meshes) {
        // 提取三条边，并确保边的顶点按固定顺序排列
        Edge edge1 = compareQVector3D(mesh.v1 , mesh.v2) ? Edge{Vertex{mesh.v1}, Vertex{mesh.v2}, mesh.normal} : Edge{Vertex{mesh.v2}, Vertex{mesh.v1}, mesh.normal};
        Edge edge2 = compareQVector3D(mesh.v2 , mesh.v3) ? Edge{Vertex{mesh.v2}, Vertex{mesh.v3}, mesh.normal} : Edge{Vertex{mesh.v3}, Vertex{mesh.v2}, mesh.normal};
        Edge edge3 = compareQVector3D(mesh.v3 , mesh.v1) ? Edge{Vertex{mesh.v3}, Vertex{mesh.v1}, mesh.normal} : Edge{Vertex{mesh.v1}, Vertex{mesh.v3}, mesh.normal};

        // 将边添加到集合中，自动去重
        uniqueEdges.insert(edge1);
        uniqueEdges.insert(edge2);
        uniqueEdges.insert(edge3);
    }

    // 将去重后的边转换为 QVector
    m_stl_model_edges = uniqueEdges.values().toVector();

    return true;
}

QVariant EdgesConvertor::getModel() const
{
    return QVariant::fromValue(m_stl_model_edges);
}

